import { ArticleApi } from '@/services/cms/CmsController';
import { ActionType, PageContainer, ProColumns, ProList, ProTable } from '@ant-design/pro-components';
import { useAccess, useNavigate, useRequest, useSearchParams } from '@umijs/max';
import { Button, Flex, message, Modal, Popover, Space, Tooltip, Typography } from 'antd';
import { Key, useRef, useState } from 'react';
import './index.css'
import Settings from './components/settings';

const SettingBar: React.FC<{ ids: number[], refresh: () => void }> = ({ ids, refresh }) => {
    return <Space>
        <Button size='small' ghost type="text" color='primary' onClick={() => {
            Modal.confirm({
                title: "恢复所选文章",
                content: "所选文章将恢复到原来状态。",
                type: "error",
                onOk: () => Promise.all(ids.map(x => ArticleApi.unrecycle(x))),
                afterClose: refresh
            });
        }}>恢复</Button>
        <Button size='small' ghost type="text" danger onClick={() => {
            Modal.confirm({
                title: "删除所选文章",
                content: "删除后将不可恢复。",
                type: "error",
                onOk: () => Promise.all(ids.map(x => ArticleApi.delete(x))),
                afterClose: refresh
            });
        }}>永久删除</Button>
    </Space>;
}

const HomePage: React.FC = () => {
    const access = useAccess()
    let navigate = useNavigate();
    let [search, setSearch] = useSearchParams()
    let [showSetting, setShowSetting] = useState<number | null>(null)
    let refs = useRef<ActionType>();

    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);

    const columns: ProColumns<Cms.ArtileList>[] = [{
        title: '标题',
        dataIndex: "title",
        search: false,
        render: (dom, entity, index, action, schema) => {
            return <Flex vertical>
                <Typography.Text>{entity.title}</Typography.Text>
                <Typography.Text style={{ maxWidth: "20rem" }} type='secondary' ellipsis={{}}>{entity.description}</Typography.Text>
            </Flex>
        },
    }, {
        title: '发布时间',
        width: "10rem",
        dataIndex: "publish_at",
        valueType: "dateTime",
        sorter: true,
        search: false
    }, {
        title: '操作',
        width: "20%",
        valueType: 'option',
        render: (_, record) => <SettingBar ids={[record.id]} refresh={() => { refs.current?.reload() }}></SettingBar>,
    }]
    return (
        <PageContainer ghost breadcrumbRender={false}
            header={{
                extra: <Space>
                    <Button onClick={() => navigate("../")}>返回</Button>
                </Space>
            }}
        >
            <Settings id={showSetting} onClose={() => setShowSetting(null)} onFinish={() => refs.current?.reload()}></Settings>
            <ProTable columns={columns} params={{}} actionRef={refs} rowKey={"id"} search={{ filterType: 'light', }}
                options={{ density: false, setting: false }}
                request={(p, o) => ArticleApi.list({ ...p, deleted: "true", order: Object.entries(o).map(([k, v]) => `${k}-${v?.startsWith("a") ? "asc" : "desc"}`).join(",") })}
                pagination={{
                    defaultCurrent: parseInt(search.get("page") || "") || 1,
                    defaultPageSize: 15,
                    showSizeChanger: true,
                    pageSizeOptions: [10, 15, 20, 25, 30, 50],
                    onChange(page, pageSize) { setSearch({ page: "" + page }) },
                }}
                rowSelection={{
                    selectedRowKeys,
                    hideSelectAll: false,
                    onChange: (keys: Key[]) => setSelectedRowKeys(keys),
                }}
                tableAlertOptionRender={(dom) => <SettingBar ids={dom.selectedRows.map(x => x.id)} refresh={() => {
                    refs.current?.reload();
                    setSelectedRowKeys([]);
                }}></SettingBar>}
            ></ProTable>
        </PageContainer >
    );
};

export default HomePage;
